package controller;

import Interceptor.Login;
import Interceptor.NavInterceptor;
import Interceptor.TopicFormValidator;
import com.jfinal.aop.Before;
import com.jfinal.core.Controller;
import com.jfinal.kit.LogKit;
import model.Reply;
import model.Topic;

import java.util.List;

/**
 * Created by Properly on 2018/5/29.
 */
public class TopicController extends Controller {
    @Before(NavInterceptor.class)
    public void index(){
        Integer id = getParaToInt(0, -1);
        Topic topic = Topic.dao.findById(id);
        if (topic == null) {
            renderHtml("指定的帖子不存在！");
            return;
        } else {String sql = "SELECT\n" +
                "t_reply.*,\n" +
                "t_user.nickname\n" +
                "FROM t_reply\n" +
                "INNER JOIN t_user ON t_reply.user_id = t_user.id\n" +
                "WHERE topic_id = ?";
            List<Reply> replies = Reply.dao.find(sql, id);
            setAttr("topic", topic);
            setAttr("replies", replies);

            renderFreeMarker("view.ftl");
        }
    }
    public void reply() {
        Integer userId = getParaToInt("user_id", -1);
        String content = getPara("content", "");
        Integer topicId = getParaToInt("topic_id", -1);
        Reply reply = new Reply();
        reply.setTopicId(topicId);
        reply.setUserId(userId);
        reply.setContent(content);
        boolean success = false;
        try {
            reply.save();
            success = true;
        } catch (Exception e) {
            LogKit.error("回复帖子失败，原因:" + e.getMessage());
        }
        String message = success ? "成功" : "失败";
        renderHtml("回复" + message);
    }
    @Before(Login.class)
    public void pub(){
        renderFreeMarker("pub.ftl");
    }

    @Before(TopicFormValidator.class)
    public void save() {
        Integer userId = getParaToInt("user_id", -1);
        Integer categoryId = getParaToInt("category_id", -1);
        //尝试默认值测试
        String content = getPara("content", "");
        String title = getPara("title", "");
        Topic topic = new Topic();
        topic.setUserId(userId);
        topic.setContent(content);
        topic.setTitle(title);
        topic.setCategoryId(categoryId);

        boolean success = false; //添加成功的标志变量
        try {
            topic.save();
            success = true;

        } catch (Exception e) {
            LogKit.error("发布失败，原因：" + e.getMessage());
        }
        String message = success ? "发布成功" : "发布失败";
        renderHtml(message + "<br><a href='/category/list'>返回</a>");

    }
}
